import { Dictionary, SeleteData } from '@/api/config'
/**
 * 遍历树结构数据源,返回带指定参数的对象组成的树
 * @param treeData 源数据
 * @param props key映射
 * @return tree
 */
export const getTreeInfor = <T, K>(treeData:Array<T>, props:{[key:string]:string}, filter?:(oldNode:T, nowNode:K)=>boolean):Array<K> => {
  const reTree:Array<K> = []
  const stack:Array<T> = []
  const generateNodestack:Array<K> = []
  let generateNode
  let node
  for (let i = 0, l = treeData.length; i < l; i++) {
    generateNode = {} as K
    //不存在过滤函数或符合过滤要求
    for (const key in props) {
      generateNode[key] = treeData[i][props[key]]
    }
    if (filter && filter(treeData[i], generateNode)) continue
    stack.push(treeData[i])
    generateNodestack.push(generateNode)
    reTree.push(generateNode)
  }
  while (node = stack.pop()) {
    generateNode = generateNodestack.pop()
    //不存在过滤函数或符合过滤要求
    if (filter && filter(node, generateNode)) continue
    if (node.children && node.children.length > 0) {
      generateNode.children = []
      for (let i = 0, l = node.children.length; i < l; i++) {
        const newNode = {} as K
        for (const key in props) {
          newNode[key] = node.children[i][props[key]]
        }
        //不存在过滤函数或符合过滤要求
        if (filter && filter(node.children[i], newNode)) continue
        generateNode.children.push(newNode)
        generateNodestack.push(newNode)
        stack.push(node.children[i])
      }
    }
  }
  return reTree
}


/**
 * 遍历树结构数据源,返回带指定参数的对象组成的列表 或过滤数据
 * @param treeData 源数据
 * @param props key映射
 * @param onlyLeaf 只返回叶节点
 * @param filter 过滤函数
 * @param filterParams 过滤函数的参数
 * @returns list
 */
export const getTreeInforByList = <T, K>(treeData:Array<T>, props?:{[key:string]:string}, onlyLeaf?:boolean, filter?:(oldNode:T, nowNode:K)=>boolean):Array<K> => {
  const stack:Array<T> = []
  const list:Array<K> = []
  for (let i = 0, l = treeData.length; i < l; i++) {
    stack.push(treeData[i])
  }
  let node
  let generateNode
  while (node = stack.pop()) {
    const notLeaf:boolean = node.children && node.children.length > 0
    if (notLeaf) {
      for (let i = 0, l = node.children.length; i < l; i++) {
        stack.push(node.children[i])
      }
    }
    //如果不是叶节点,且开启了onlyLeaf 则跳过
    if (notLeaf && onlyLeaf) continue
    generateNode = {} as T
    //没有映射则是原来的数据
    if (props) {
      for (const key in props) {
        generateNode[key] = node[props[key]]
      }
    } else {
      for (const key in node) {
        generateNode[key] = node[key]
      }
    }
    //不存在过滤函数或符合过滤要求
    if (!filter || filter(node, generateNode)) list.push(generateNode)
  }
  return list
}

interface TreeData<T>{
  children?:Array<T>
}

/**
 * 树结构的遍历 更普适的方法
 * @param treeData 树数据
 * @param visit 访问函数
 * @param order 顺序访问
 */
export const traveTree = <T extends TreeData<T>>(treeData:Array<T>, visit:(node:T)=>void, order?:boolean) => {
  if (!treeData.length) return
  const stack:Array<T> = []
  if (order) {
    for (let i = treeData.length - 1; i >= 0; i--) {
      stack.push(treeData[i])
    }
  } else {
    for (let i = 0, l = treeData.length; i < l; i++) {
      stack.push(treeData[i])
    }
  }
  let node:T|undefined = undefined
  while (node = stack.pop()) {
    visit(node)
    if (node.children && node.children.length) {
      if (order) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push(node.children[i])
        }
      } else {
        for (let i = 0, l = node.children.length; i < l; i++) {
          stack.push(node.children[i])
        }
      }
    }
  }
}

/**
 * 树结构的遍历  层次遍历
 * @param treeData 树数据
 * @param visit 访问函数
 */
export const traveTreeByLevel = <T extends TreeData<T>>(treeData:Array<T>, visit:(node:T, level:number)=>void) => {
  if (!treeData.length) return
  let queue:Array<T> = []
  for (let i = 0, l = treeData.length; i < l; i++) {
    queue.push(treeData[i])
  }
  let level = 0
  while (queue.length) {
    const childrenQueue:Array<T> = []
    queue.forEach((node) => {
      visit(node, level)
      if (node.children) {
        node.children.forEach((childrenNode) => {
          childrenQueue.push(childrenNode)
        })
      }
    })
    queue = childrenQueue.concat([])
    level++
  }
}

//深度遍历对象
export const deepTrave = (data:unknown, visit:(element:unknown)=>void) => {
  const stack:Array<unknown> = [data]
  let element:unknown = null
  while (stack.length) {
    element = stack.pop()
    visit(element)
    if (typeof element === 'object' || Array.isArray(element)) {
      for (const key in element) {
        stack.push(element[key])
      }
    }
  }
}


//获取某个属性
export const getObjectByKey = <T>(object:Array<T>, key:string, value:string):T|null => {
  for (const k in object) {
    if (object[k][key] === value) return object[k]
  }
  return null
}

//获取是否选择两个打印机
export const getHasPrint = (barcodePrintName:string, reprotPrintName:string):boolean => {
  const barcode = localStorage.getItem(barcodePrintName)
  const reprot = localStorage.getItem(reprotPrintName)
  return (barcode && reprot) ? true : false
}

export const second = 1000
export const minute = second * 60
export const hour = minute * 60
export const day = hour * 24

//获取年月日 可拆分函数
export const getYearMonthDay = (time:number):Array<number> => {
  const timestr = new Date(time)
  const year = timestr.getFullYear()
  const month = timestr.getMonth() + 1
  const day = timestr.getDate()
  return [year, month, day]
}
//获取年月日 字符串
export const getYearMonthDayStr = (time:number):string => {
  const timestr = new Date(time)
  const year = timestr.getFullYear()
  let month :string|number = timestr.getMonth() + 1
  let day :string|number = timestr.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}

//获取时间字符串 格式 yyyy-mm-dd hh:mm:ss
export const getYMDHMSStr = (time:number):string => {
  const timeDate = new Date(time)
  const year = timeDate.getFullYear()
  let month :string|number = timeDate.getMonth() + 1
  let day :string|number = timeDate.getDate()
  let hours:string|number = timeDate.getHours()
  let minutes:string|number = timeDate.getMinutes()
  let seconds:string|number = timeDate.getSeconds()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  if (hours < 10) hours = '0' + hours
  if (minutes < 10) minutes = '0' + minutes
  if (seconds < 10) seconds = '0' + seconds
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

//获取年份
export const getYear = (time:number):number => {
  const timestr = new Date(time)
  const year = timestr.getFullYear()
  return year
}

//获取一年的时间
export const getAYearStr = (time:number):Array<string> => {
  const timestr = new Date(time)
  const year = timestr.getFullYear()
  let month :string|number = timestr.getMonth() + 1
  let day :string|number = timestr.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return [year - 1 + '-' + month + '-' + day, year + '-' + month + '-' + day]
}

import dayjs, { Dayjs } from 'dayjs'
//根据YYYY-DD获取这个月开始的时间
export const getMonthStartDate = (month:string):string => {
  //
  return month + '-01 00:00:00'
}

//根据YYYY-DD获取这个月结束的时间
export const getMonthEndDate = (month:string):string => {
  const total = dayjs(month).daysInMonth()
  return month + '-' + total + ' 23:59:59'
}

//根据YYYY-DD获取这个月开始的时间戳
export const getMonthStartTime = (month:string):number => {
  const date = new Date(month + '-01 00:00:00')
  return date.getTime()
}

//根据YYYY-DD获取这个月的天数
export const getMonthDays = (month:string):number => {
  return dayjs(month).daysInMonth()
}

//禁用今天之后日期
export const disabledAfterDate = (current: Dayjs):boolean => {
  return current && current > dayjs().endOf('day')
}

type RangeUnit='second' | 'minute' | 'hour' | 'day' | 'month' | 'year'
//选择日期范围
export const disabledRange = (current:Dayjs, range:[string, string]|undefined, step:number, type:RangeUnit, endOf?:'day'|'second') => {
  let min:Dayjs|undefined
  let max:Dayjs|undefined
  if (range && range[0]) {
    const start = dayjs(range[0])
    max = start.add(step, type)
  }
  if (range && range[1]) {
    const end = dayjs(range[1])
    min = end.subtract(step, type)
  }
  if (min && current < min.endOf(endOf ? endOf : 'day')) {
    return true
  }
  if (max && current > max.endOf(endOf ? endOf : 'day')) {
    return true
  }
  return false
}

//检查范围,清除数据
export const checkRange = (range:Array<string>|undefined, step:number, type:RangeUnit, clearStart?:boolean, endOf?:'day'|'second'):boolean => {
  if (!range) return false
  let min:Dayjs|undefined
  let max:Dayjs|undefined
  let start:Dayjs|undefined
  let end:Dayjs|undefined
  if (range[0] && range[1]) {
    start = dayjs(range[0])
    max = start.add(step, type)
    end = dayjs(range[1])
    min = end.subtract(step, type)
    if (clearStart && end > max.endOf(endOf ? endOf : 'day')) {
      range[0] = ''
      return false
    } else if (start < min.endOf(endOf ? endOf : 'day')) {
      range[1] = ''
      return false
    }
  }
  return false
}

//下载文件
export const downFile = (name:string, buffer:ArrayBuffer) => {
  const blob = new Blob([buffer])
  const a = document.createElement('a')
  // document.appendChild(a)
  a.style.display = 'none'
  a.download = name
  const url = URL.createObjectURL(blob)
  a.href = url
  a.click()
  URL.revokeObjectURL(url)
  // document.removeChild(a)
}

import { BASE_SHORTNAME, UseSuffix } from '@/store/config'
//下载文件
export const downLacolFile = (name:string, _url:string) => {
  const url = UseSuffix ?  '/' + BASE_SHORTNAME + _url : _url
  const a = document.createElement('a')
  a.style.display = 'none'
  a.download = name
  a.href = url
  a.click()
  URL.revokeObjectURL(url)
  // document.removeChild(a)
}

const headMap = {'xlsx':[0x50, 0x4b, 0x03, 0x04]}
//文件头检测
export const fileHeadCheck = (file:File, fileType:string):Promise<null> => {
  return new Promise<null>((resolve, reject) => {
    const headData:Array<number> = headMap[fileType]
    if (headData && headData.length && headData.length <= file.size) {
      const fileHead = file.slice(0, headData.length)
      fileHead.arrayBuffer().then((buffer) => {
        const dataView:DataView = new DataView(buffer)
        //防止文件头过长引起的数字溢出,这里一个字节一个字节的比较 也不需要考虑字节序
        for (let i = 0, l = headData.length; i < l; i++) {
          if (dataView.getUint8(i) !== headData[i]) {
            reject(null)
            return
          }
        }
        resolve(null)
      }).catch(() => {
        reject(null)
      })
    } else {
      //
      reject(null)
    }
  })
}

import * as mathjs from 'mathjs'
export type SizeUnit='B'|'KB'|'MB'|'GB'
const SizeUnitArr:Array<SizeUnit> = ['B', 'KB', 'MB', 'GB']
const SizeUnitStep:Array<number> = [1, 1024, 1024, 1024]
//文件大小检测
export const fileSizeCheck = (fileSize:number, maxSize:number, unit:SizeUnit):boolean => {
  let size = fileSize
  for (let i = 0, l = SizeUnitArr.length; i < l; i++) {
    size = mathjs.divide(size, SizeUnitStep[i])
    if (SizeUnitArr[i] === unit) {
      break
    }
  }
  return size <= maxSize
}

//浅拷贝对象
export const shallowCopy = <T>(obj:{[key:string]:T}):{[key:string]:T} => {
  const newObj:{[key:string]:T} = {}
  for (const key in obj) {
    newObj[key] = obj[key]
  }
  return newObj
}

//线性同余生成随机数
export const random = () => {
  //
}

/**
 * 有序数组对比去重
 * @param sourceArr 源数组
 * @param doubleArr 重复数据数组
 * @returns 去重后的数据
 */
export const removeDoubleBySort = <T>(sourceArr:Array<T>, doubleArr:Array<T>, key?:string):Array<T> => {
  const arr:Array<T> = []
  for (let i = 0, k = 0, il = sourceArr.length, kl = doubleArr.length; i < il; i++) {
    const sourceItem = sourceArr[i]
    let flag = true
    if (k < kl) {
      const doubleItem = doubleArr[k]
      if (key && sourceItem[key] === doubleItem[key]) {
        k++
        flag = false
      }
      else if (sourceItem === doubleItem) {
        k++
        flag = false
      }
    }
    if (flag) arr.push(sourceItem)
  }
  return arr
}

/**
 * 简易无序数组对比去重
 * @param sourceArr 源数组
 * @param doubleArr 重复数据数组
 * @returns 去重后的数据
 */
export const removeDoubleByUnSort = <T>(sourceArr:Array<T>, doubleArr:Array<T>, sort?:boolean, sortkey?:string):Array<T> => {
  let arr:Array<T> = []
  //转为有序去重
  if (sort) {
    if (sortkey) {
      sourceArr.sort((a, b) => {
        return a[sortkey] - b[sortkey]
      })
      doubleArr.sort((a, b) => {
        return a[sortkey] - b[sortkey]
      })
    } else {
      sourceArr.sort()
      doubleArr.sort()
    }
    arr = removeDoubleBySort(sourceArr, doubleArr, sortkey)
  }
  //暴力去重
  else {
    for (let i = 0, l = sourceArr.length; i < l; i++) {
      const sourceItem = sourceArr[i]
      let flag = true
      for (let k = 0, kl = doubleArr.length; k < kl; k++) {
        const doubleItem = doubleArr[k]
        if (sortkey && sourceItem[sortkey] === doubleItem[sortkey]) {
          flag = false
          break
        }
        else if (sourceItem === doubleItem) {
          flag = false
          break
        }
      }
      if (flag) arr.push(sourceItem)
    }
  }
  return arr
}

//找到最小和最大的
export const findMinMax = (sourceArr:Array<number|string>):Array<number|string> => {
  let min = sourceArr[0]
  let max = sourceArr[0]
  for (let i = 1, l = sourceArr.length; i < l; i++) {
    const now = sourceArr[i]
    if (now < min) min = now
    if (now > max) max = now
  }
  return [min, max]
}


//判断数字数组A和数字数组B是否有交集
export const checkCopyData = (arrA:Array<number|string>, arrB:Array<number|string>):boolean => {
  for (let i = 0, la = arrA.length; i < la; i++) {
    const nowA = arrA[i]
    let flag = false
    for (let k = 0, lb = arrB.length; k < lb; k++) {
      const nowB = arrB[k]
      if (nowB === nowA) {
        flag = true
        break
      }
    }
    if (flag) return true
  }
  return false
}


export interface CRule{
  reg:RegExp
  errorMsg:string
}

//uni表单验证
export interface CFormRule{
  name:string
  rules:Array<CRule>
}

//单条验证
export const checkrule = (rule:CRule, value:string) => {
  return rule.reg.test(value)
}

interface RuleVerify{
  success:boolean
  errorRule:CRule|null
  errorName:string|null
}

//验证表单数据
export const checkRules = (rules:Array<CFormRule>, obj:{[key:string]:string}):RuleVerify => {
  const verify:RuleVerify = {success:true, errorName:null, errorRule:null}
  for (let i = 0, l = rules.length; i < l; i++) {
    const rule = rules[i]
    const value:string = obj[rule.name]
    let flag = false
    for (let i = 0, l = rule.rules.length; i < l; i++) {
      const reg = rule.rules[i]
      if (!checkrule(reg, value)) {
        verify.success = false
        verify.errorName = rule.name
        verify.errorRule = reg
        flag = true
        break
      }
    }
    if (flag) break
  }
  return verify
}


//转换数据
export const transfData = <K, T>(from:K, props:Dictionary<string>):T => {
  const data = {} as T
  for (const key in props) {
    data[props[key]] = from[key]
  }
  return data
}

//转换数组数据
export const transfArrData = <K, T>(fromArr:Array<K>, props:Dictionary<string>):Array<T> => {
  const arr:Array<T> = []
  fromArr.forEach((item) => {
    arr.push(transfData<K, T>(item, props))
  })
  return arr
}

export interface DicData{
  dictItemName:string
  dictItemCode:string
}

//转换字典数据
export const transfDicArrData = (dicArr:Array<DicData>|undefined|null):Array<SeleteData> => {
  if (!dicArr || dicArr.length === 0) {
    return []
  } else {
    return transfArrData(dicArr, {'dictItemName':'label', dictItemCode:'value'})
  }
}


/**常用的正则表达式 */

//正整数
export const PositiveInteger = /^[1-9][0-9]*$/
//国内手机号
export const PhoneNumber = /^1[0-9]{10}$/
//路由
export const RouteUrl = /^(\/[A-Za-z]+)+$$/
// 不能输入中文并且包含空格
export const ChineseMat = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g
// 手机或者座机同时
export const PhoneLandline = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/
//中文,字母,数字,特殊符号(不匹配空白字符)
export const Normal = /^\S+$/
//字母、数字、特殊符号(不匹配中文)
export const NoChinese = /^[^\u4e00-\u9fa5]+$/
//字母、数字、特殊符号(不匹配中文 空白符)
export const NoChineseEmty = /^([^\u4e00-\u9fa5\s])+$/
//中文,字母
export const Chinese = /^[\u4E00-\u9FA5]+$/
//中文,字母
export const ChineseLetter = /^[\u4E00-\u9FA5A-Za-z]+$/
//英文字母
export const Letter = /^[A-Za-z]+$/
//数字
export const Number = /^[0-9]+$/
//特殊字符
export const SpecialCharacters = /^[@#$%^*_]+$/

//字母（前后不允许有空格，中间允许）
export const LetterNoEmty = /^[A-Za-z][A-Za-z^\s]*[A-Za-z]$|^[A-Za-z]$/
// 首尾不能为空格
export const NotLeadingAndTrailingSpaces = /^[^\s]+(\s+[^\s]+)*$/

// 不包含数字
export const NoNumber = /^[^0-9]+$/


//汉字、字母、数字
export const ChineseAlphanumeric = /^[\u4E00-\u9FA5A-Za-z0-9]+$/

//字母、数字
export const Alphanumeric = /^[A-Za-z0-9]+$/

//字母,数字，符号
export const Collect = /^[A-Za-z0-9@#$%^*_]+$/

//密码(中)
//数字和字母
export const PassWordLv2_1 = /^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9@#$%^*_]+$/
//数字和符号
export const PassWordLv2_2 = /^(?=.*\d)(?=.*[@#$%^*_])[A-Za-z0-9@#$%^*_]+$/
//字母和符号
export const PassWordLv2_3 = /^(?=.*[A-Za-z])(?=.*[@#$%^*_])[A-Za-z0-9@#$%^*_]+$/
//密码(强) 数字,大小写字母,符号
export const PassWord = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^*_])[A-Za-z0-9@#$%^*_]+$/


// 邮箱
export const Email =  /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
// 中文、字母、空格(姓名)
export const Linkman = /^([\u4E00-\u9FA5A-Za-z0-9\uFF0E\,\s](?!\u3000))+$/
//数字,包含小数点以及负号,小数点后5位
export const NegativeNumber = /^(-)?(([1-9]{1}\d*)((\.\d{1,5})?)$|^-?(0{1}))((\.\d{1,5})?)$/
// 字母和空格
export const EnglishSpace = /^[A-Za-z ]+$/

// 3位整数
export const Number_3 = /^[0-9]{1,3}$/
// 4位整数
export const Number_4 = /^[0-9]{1,4}$/
// 保留一位小数，包括小数最多三位数值
export const Number_Decimal_3 = /(^[0-9]{1,2}$)|(^[0-9]{1,2}[\.][0-9]{1}$)/
// 保留一位小数，包括小数最多四位数值
export const Number_Decimal_4 = /(^[0-9]{1,4}$)|(^[0-9]{1,3}[\.][0-9]{1}$)/
// 保留两位小数，包括小数最多五位数值
export const Number_Decimal_5 = /(^[0-9]{1,5}$)|(^[0-9]{1,3}[\.][0-9]{1,2}$)/

//身份证
export const IdCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
export const IdCards = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)|(^\d{3}\*{8}\d{4}$)|(^\d{3}\*{11}\d{4}$)|(^\d{3}\*{11}\d{3}(\d|X|x)$)/

//价格，带两位小数的数字
export const Price = /^(([1-9]{1}\d*)|(0{1}))(\.{0,1}\d{0,2})$/

//年月日
export const YYYYMMDD = /^[0-9]{4}(((0[13578]|(10|12))(0[1-9]|[1-2][0-9]|3[0-1]))|(02(0[1-9]|[1-2][0-9]))|((0[469]|11)(0[1-9]|[1-2][0-9]|30)))$/
//年月日时分秒 简易
export const YYYYMMDDHHSSMM = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/
// 数字和小数点
export const NumberDot =  /^[0-9\.]+$/

import JsBarcode from 'jsbarcode'
//生成条形码base64数据
export const getBarcodeImgData = (barcode:string, width = 100, height = 30) => {
  const canvas = document.createElement('canvas')
  if (!canvas.getContext) return false
  JsBarcode(canvas, barcode, {format:'CODE128', width: width, height: height, displayValue:false, margin:0})
  return canvas.toDataURL('image/jpeg', 1)
}

export interface IdCardInfor{
  age:number|null //年龄
  sex:number|null //性别
}

//身份证校验位验证 15位不校验
export const checkIdCardNum = (id:string):boolean => {
  if (id.length < 18) {
    return true
  } else {
    //日期不能为00
    const num = id[17]
    const addArr = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    const valArr = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
    let index = 0
    for (let i = 0; i < 17; i++) {
      index += +id[i] * addArr[i]
    }
    index = index % 11
    return num + '' === valArr[index] + ''
  }
}

//身份证信息读取
export const getIdCardInfor = (id:string, _maxage?:number, _minage?:number):IdCardInfor => {
  const baseInfor:IdCardInfor = {age:null, sex:null}
  if (IdCard.test(id)) {
    //性别
    const sexCode = id.length === 18 ? +id[16] : +id[15]
    baseInfor.sex = sexCode & 1 ? 1 : 2
    //年龄
    if (id.length === 18) {
      const maxAge = _maxage ? _maxage : 150
      const minAge = _minage ? _minage : 0
      //获取出生年月日
      const yearBirth = +id.substring(6, 10)
      const monthBirth = +id.substring(10, 12)
      const dayBirth = +id.substring(12, 14)
      //获取当前年月日并计算年龄
      const myDate = new Date()
      const monthNow = myDate.getMonth() + 1
      const dayNow = myDate.getDate()
      //得到虚岁
      let age = myDate.getFullYear() - yearBirth
      //未满岁
      if (monthNow < monthBirth || (monthNow === monthBirth && dayNow < dayBirth)) {
        age--
      }
      baseInfor.age = age
      //不能超过或小于
      if (age > maxAge || age < minAge) {
        baseInfor.sex = null
        baseInfor.age = null
      }
      //检验位验证 生日检验
      const yyyymmdd = id.substring(6, 14)
      if (!checkIdCardNum(id) || !YYYYMMDD.test(yyyymmdd)) {
        baseInfor.sex = null
        baseInfor.age = null
      }
    }
  }
  return baseInfor
}


/**
 * @description: 检查是否是json
 * @param {*} str
 * @return {*}
 */
export const checkIsJSON = (str: string) => {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str)
      if (typeof obj === 'object' && obj) {
        return true
      } else {
        return false
      }
    } catch (e) {
      return false
    }
  }
  return false
}